<template>
  <div class="app-container">
    <el-form label-position="right" label-width="120px" :model="readerForm" :rules="rules" style="width: 80%;">
    
      <el-form-item label="数据库源：" prop="sourceId">
        <el-select v-model="readerForm.sourceId" filterable  @change="rDsChange">
          <el-option
            v-for="item in rDsList"
            :key="item.id"
            :label="item.sourceName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="数据库表名：" prop="tableId">
        <el-select v-model="readerForm.tableId" allow-create default-first-option filterable  @change="rTbChange">
          <el-option v-for="item in rTbList" :key="item.id" :label="item.tableName" :value="item.id" />
        </el-select>
      </el-form-item>
 
  
      <el-form-item label="SQL语句：">
        <el-input v-model="readerForm.querySql" :autosize="{ minRows: 3, maxRows: 20}" type="textarea" placeholder="sql查询，一般用于多表关联查询时才用"  />
        <el-button type="primary" @click.prevent="getColumns('reader')">解析字段</el-button>
      </el-form-item>
      <el-form-item label="切分字段：">
        <el-input v-model="readerForm.splitPk" placeholder="切分主键"  />
      </el-form-item>
      <el-form-item label="表所有字段：">
        <el-checkbox
          v-model="readerForm.checkAll"
          :indeterminate="readerForm.isIndeterminate"
          @change="rHandleCheckAllChange"
        >全选
        </el-checkbox>
        <div style="margin: 15px 0;" />
        <el-checkbox-group v-model="readerForm.columns" @change="rHandleCheckedChange">
          <el-checkbox v-for="c in rColumnList" :key="c.id" :label="c">{{ c.columnName }}</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="是否增量：" prop="isIncrement">
        <el-select v-model="readerForm.isIncrement" class="filter-item" placeholder="请选择增量状态" @change="choseType">
              <el-option v-for="item in dictList('is_increment')" :key="'type' + item.label" :label="item.label"
                :value="item.value" />
            </el-select>
      </el-form-item>
      <el-form-item label="where条件：" prop="where">
        <el-input v-model="readerForm.where" placeholder="where条件，不需要再加where。增量模式需取时间范围增量" type="textarea"  />
      </el-form-item>
    </el-form>

    
  </div>
</template>

<script>
// import * as dsQueryApi from '@/api/dts/metadata-query'
// import { list as jdbcDsList } from '@/api/dts/datax-jdbcDatasource'
import Bus from '../busReader'
import { listDataSource } from '@/api/metadata/sqlconsole'
import { getTableList } from '@/api/masterdata/masterdataTable'
import { fetchcolumnList } from '@/api/metadata/column'
export default {
  name: 'TableReader',
  data() {
    return {
      rDsList: [],
      rTbList: [],
      schemaList: [],
      columns:[],
      rColumnList:[],//列名数组
      loading: false,
      active: 1,
      customFields: '',
      customType: '',
      customValue: '',
      dataSource: '',
      readerForm: {
        sourceId: undefined,
        sourceName:undefined,
        columns: [],
        tableName:'',
        tableId:'',
        checkAll: false,
        isIndeterminate: true,
        splitPk: '',
        tableSchema: '',
        querySql:'',//sql语句
        isIncrement:'',
        where:'',//where语句
      },
      rules: {
        sourceId: [{ required: true, message: '数据库源为必填项', trigger: 'change' }],
        tableId: [{ required: true, message: '数据库表名为必填项', trigger: 'change' }],
     
      }
    }
  },
  watch: {
    'readerForm.sourceId': function(oldVal, newVal) {
      if (this.dataSource === 'postgresql' || this.dataSource === 'oracle' || this.dataSource === 'sqlserver' || this.dataSource === 'hana') {
        this.getSchema()
      } else {
        this.getTables('reader')
      }
    }
  },
  created() {
    this.getJdbcDs()
  },
  methods: {
    //获取列名
    rTbChange(id){
      this.rTbList.forEach(item=>{
        if(item.id==id){
          this.readerForm.tableName=item.tableName
        }
      })
      fetchcolumnList({sourceId:id}).then(res => {
                if (res.data.code === 0) {
                    this.rColumnList = res.data.data
                    console.log(this.rColumnList,'list')
                } else {
                    this.$message.error(res.data.msg)
                }
            })
    },
    rest(){
      this.rColumnList=[]
      this.readerForm= {
        sourceId: undefined,
        sourceName:undefined,
        columns: [],
        tableName:'',
        tableId:'',
        checkAll: false,
        isIndeterminate: true,
        splitPk: '',
        tableSchema: '',
        querySql:'',//sql语句
        where:''
      }
      this.rTbList=[]
    },
    // 获取可用数据源
    getJdbcDs() {
      this.loading = true
      listDataSource().then(response => {
        if (response.data.code == 200) {
        this.rDsList =  response.data.data
        this.loading = false
        }
      })
    },
    // 获取表名
    getTables(type) {
     
      if (type === 'reader') {
        let obj = {}
        if (this.dataSource === 'postgresql' || this.dataSource === 'oracle' || this.dataSource === 'sqlserver' || this.dataSource === 'hana') {
          obj = {
            sourceId: this.readerForm.sourceId,
            tableSchema: this.readerForm.tableSchema
          }
        } else {
          obj = {
            sourceId: this.readerForm.sourceId
          }
        }
        // 组装
        getTableList({ sourceId: this.readerForm.sourceId }).then(res => {
                if (res.data.code == 200) {
                  this.rTbList = res.data.data
                }
            })
      }
    },
    getSchema() {
      const obj = {
        sourceId: this.readerForm.sourceId
      }
      // dsQueryApi.getTableSchema(obj).then(response => {
      //   this.schemaList = response
      // })
      getTableList(obj).then(res => {
                if (res.data.code === 200) {
                  this.schemaList = res.data.data
                }
            })
    },
    // schema 切换
    schemaChange(e) {

      this.readerForm.tableSchema = e
      // 获取可用表
      this.getTables('reader')
    },
    // reader 数据源切换
    rDsChange(e) {
      // 清空
      this.readerForm.tables=[]//选中表清空
      this.readerForm.tableName = ''
      this.readerForm.sourceId = e
      this.rDsList.find((item) => {
        if (item.id === e) {
          this.readerForm.sourceName=item.sourceName
          this.dataSource = item
        }
      })
      Bus.sourceId = e
      this.$emit('selectDataSource', this.dataSource)
      // 获取可用表
      this.getTables('reader')
    },
    rHandleCheckAllChange(val) {
      this.readerForm.columns = val ? this.rColumnList : []
      this.readerForm.isIndeterminate = false
    },
    rHandleCheckedChange(value) {
      console.log(value)
      const checkedCount = value.length
      this.readerForm.checkAll = checkedCount === this.rColumnList.length
      this.readerForm.isIndeterminate = checkedCount > 0 && checkedCount < this.rColumnList.length
    },
    getData() {
      // if (Bus.sourceId) {
      //   this.readerForm.sourceId = Bus.sourceId
      // }
      return this.readerForm
    }
  }
}
</script>
